package gen.tools.test;

import gen.tools.Widgets;
import gen.tools.structures.DepInfo;
import gen.tools.structures.RreqTestResult;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class CreTestResult extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CreTestResult() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		response.setCharacterEncoding(wid.UIcodeSet);
		response.setContentType("application/text");
		
		final String strSQL = "INSERT INTO mptestresultwithreqs (modId,creatorId,jobSN,isDailyBuild,cDT,reqId,testTaskStatusId) VALUES (?,?,?,?,?,?,?)";
		final RreqTestResult reqs = new Gson().fromJson( request.getParameter("reqs"), RreqTestResult.class);
		final DepInfo dif = new Gson().fromJson( request.getParameter("dif"), DepInfo.class);
		final String empId = request.getParameter("empId");
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		final String jobName = dif.isDailyBuild()?"MR":"OL"+"_"+dif.getSubsysId()+"_"+dif.getModId();
		try {
			conn = wid.getConn();
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, jobName);
			ps.setString(2, empId);
			ps.setInt(3, dif.getJobSN());
			ps.setString(4, dif.isDailyBuild()?"t":"f");
			ps.setTimestamp(5, wid.cDT());
			for(int i=0; i < reqs.getReqs().size();i++) {
				ps.setInt(6, reqs.getReqs().get(i).getReqId());
				ps.setInt(7, reqs.getReqs().get(i).getResult());
				ps.execute();
			}
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write("OK");
		
	}

}
